package consul

import (
	"fmt"
	consulApi "github.com/hashicorp/consul/api"
	"order-srv/libs"
)

// 把当前项目的 grpc 微服务，在consul上 注册/注销。在 main。go 内调用

// ServiceRegisterMain 服务注册
func ServiceRegisterMain() {
	// 1.注册服务信息
	reg := consulApi.AgentServiceRegistration{}
	reg.ID = fmt.Sprintf("%d", libs.AppConfig.Port)
	reg.Name = libs.AppConfig.Name
	reg.Address = libs.AppConfig.IP
	reg.Port = libs.AppConfig.Port
	reg.Tags = []string{fmt.Sprintf("%s:%d", reg.Address, reg.Port)}

	// 2.设置健康检查
	check := consulApi.AgentServiceCheck{}
	check.Interval = "5s"
	check.GRPC = fmt.Sprintf("%s:%d", reg.Address, reg.Port)

	// 3.添加检查
	reg.Check = &check

	// 4.注册服务
	err := consulClient.Agent().ServiceRegister(&reg)
	if err != nil {
		panic(err)
		return
	}
	// http://106.13.184.120:8500/ui/dc1/services 服务面板
	// http://127.0.0.1:8500/v1/agent/services	查看注册服务
}

// ServiceRegisterGateway 把 gateway 也注册到 consul 上
func ServiceRegisterGateway() {
	port := libs.AppConfig.GatewayPort

	// 1.注册服务信息
	reg := consulApi.AgentServiceRegistration{}
	reg.ID = fmt.Sprintf("%d", port)
	reg.Name = libs.AppConfig.Name + "-gateway"
	reg.Address = libs.AppConfig.IP
	reg.Port = port
	reg.Tags = []string{fmt.Sprintf("%s:%d", reg.Address, reg.Port)}

	// 2.设置健康检查
	check := consulApi.AgentServiceCheck{}
	check.Interval = "5s"
	check.HTTP = fmt.Sprintf("http://%s:%d/health", reg.Address, reg.Port)
	fmt.Println(check.HTTP)

	// 3.添加检查
	reg.Check = &check

	// 4.注册服务
	err := consulClient.Agent().ServiceRegister(&reg)
	if err != nil {
		panic(err)
		return
	}
	// http://106.13.184.120:8500/ui/dc1/services 服务面板
	// http://127.0.0.1:8500/v1/agent/services	查看注册服务
}

// ServiceRegisterBiz 把 biz 也注册到 consul 上
func ServiceRegisterBiz() {
	port := libs.AppConfig.BizPort

	// 1.注册服务信息
	reg := consulApi.AgentServiceRegistration{}
	reg.ID = fmt.Sprintf("%d", port)
	reg.Name = libs.AppConfig.Name + "-api"
	reg.Address = libs.AppConfig.IP
	reg.Port = port
	reg.Tags = []string{fmt.Sprintf("%s:%d", reg.Address, reg.Port)}

	// 2.设置健康检查
	check := consulApi.AgentServiceCheck{}
	check.Interval = "5s"
	check.HTTP = fmt.Sprintf("http://%s:%d/health", reg.Address, reg.Port)
	fmt.Println(check.HTTP)

	// 3.添加检查
	reg.Check = &check

	// 4.注册服务
	err := consulClient.Agent().ServiceRegister(&reg)
	if err != nil {
		panic(err)
		return
	}
	// http://106.13.184.120:8500/ui/dc1/services 服务面板
	// http://127.0.0.1:8500/v1/agent/services	查看注册服务
}

// ServiceDeregister 服务注销
func ServiceDeregister() {
	_ = consulClient.Agent().ServiceDeregister(fmt.Sprintf("%d", libs.AppConfig.Port))        // 注销主服务
	_ = consulClient.Agent().ServiceDeregister(fmt.Sprintf("%d", libs.AppConfig.GatewayPort)) // 注销gateway
	_ = consulClient.Agent().ServiceDeregister(fmt.Sprintf("%d", libs.AppConfig.BizPort))     // 注销gateway
}
